package com.jt.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;
import sun.text.normalizer.UnicodeSet;

import java.util.List;

/**
 * @author 张琪
 * @date 2020/12/12
 * @describe
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/getMsg")
    public String doTest() {
        System.out.println("good");
        return "测试成功!!";
    }

    @GetMapping("/check/{param}/{type}")
    public JSONPObject doCheck(@PathVariable String param, @PathVariable Integer type, String callback) {
        System.out.println(param + type);
        boolean flag = userService.findInfo(param, type);
        System.out.println(flag);
        SysResult result = SysResult.success(flag);

        System.out.println(ObjectMapperUtil.toJson(result));

        return new JSONPObject(callback, result);
    }

    @RequestMapping("/findUserList")
    public List<User> doFindUserList() {
        List<User> users = userService.findUserList();
        System.out.println("UserController.doFindUserList");
        return users;
    }

    @RequestMapping("/query/{ticket}")
    public JSONPObject findUserByTicket(@PathVariable String ticket, String callback) {
//        如何获取用户信息, 从redis中获取数据
        if (!jedisCluster.exists(ticket)) {
            return new JSONPObject(callback, SysResult.fault());
        } else {
//            如果ticket存在, 则从redis缓存中获取已经认证过的用户信息, 通过JSONP实现跨域访问
            String userJson = jedisCluster.get(ticket);
            SysResult sysResult = SysResult.success(userJson);
            return new JSONPObject(callback, sysResult);
        }
    }

}
